/*
 *  Copyright 2009 Lucas Nazário dos Santos
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package net.sourceforge.retriever.sample;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sourceforge.retriever.Retriever;
import net.sourceforge.retriever.analyzer.Analyzer;
import net.sourceforge.retriever.fetcher.Resource;
import net.sourceforge.retriever.filter.URLRegexFilter;

/*
 * This sample shows how to discover all pages referenced by some Web site.
 */
public class CrawlingPagesPointedByStelasWebSite {


	public static void main(final String[] args) throws MalformedURLException {

		final Retriever crawler = new Retriever();

		crawler.addSeed(new URL("http://www.stela.org.br/"));

		// Tells the crawler to stay within the domain stela.org.br
		final URLRegexFilter filter = new URLRegexFilter();
		filter.addRegex(".*stela\\.org\\.br.*");
		crawler.setFilter(filter);

		// Prints all resources pointed by http://www.stela.org.br/
		crawler.setAnalyzer(new Analyzer() {
			private final Set<String> urlsAlreadyPrinted = new HashSet<String>();

			public void analyze(final Resource resource, final Map<String, Object> additionalInfo) {
				final List<String> innerURLs = new ArrayList<String>(resource.getInnerURLs());
				if (innerURLs.size() > 0) {
					this.filterURLsFromStela(innerURLs);
					this.printInnerURLs(innerURLs);
				}
			}

			private void filterURLsFromStela(final List<String> innerURLs) {
				final List<String> urlsToRemove = new ArrayList<String>();
				for (String innerURL : innerURLs) {
					if (innerURL.matches(".*stela\\.org\\.br.*")) {
						urlsToRemove.add(innerURL);
					}
				}

				innerURLs.removeAll(urlsToRemove);
			}

			private void printInnerURLs(final List<String> innerURLs) {
				for (String innerURL : innerURLs) {
					if (this.urlsAlreadyPrinted.contains(innerURL)) continue;

					this.urlsAlreadyPrinted.add(innerURL);
					System.out.println(innerURL);
				}
			}
		});

		crawler.start();
	}
}